let App = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataType: 'all',
    list: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.dataType = options.type || 'all';
    this.setData({
      dataType: this.data.dataType
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (!App.checkIsLogin()) {
      App.showError("请先登录", function () {
        wx.navigateTo({
          url: '/pages/user/index',
        })
      })
    } else {
      // 获取订单列表
      this.getOrderList(this.data.dataType);
    }
  },

  /**
   * 获取订单列表
   */
  getOrderList: function (dataType) {
    let _this = this;

    App._get('/order/list', {
      status: dataType,
      token: wx.getStorageSync('token')
    }, function (result) {
        _this.setData({
        list: result.data
      });
    });
  },

  /**
   * 切换标签
   */
  bindHeaderTap: function (e) {
    this.setData({
      dataType: e.target.dataset.type
    });
    // 获取订单列表
    this.getOrderList(e.target.dataset.type);
  },

  /**
   * 取消订单
   */
  cancelOrder: function (e) {
    let _this = this;
    let order_id = e.currentTarget.dataset.id;
    wx.showModal({
      title: "提示",
      content: "确认取消订单？",
      success: function (o) {
        if (o.confirm) {
          App._post_form('order/cancel', {
            id: order_id,
            token: wx.getStorageSync('token')
          }, function (result) {
            _this.getOrderList(_this.data.dataType);
          });
        }
      }
    });
  },

  /**
   * 确认收货
   */
  receipt: function (e) {
    let _this = this;
    let order_id = e.currentTarget.dataset.id;
    wx.showModal({
      title: "提示",
      content: "确认收到商品？",
      success: function (o) {
        if (o.confirm) {
          App._post_form('user.order/receipt', {
            order_id
          }, function (result) {
            _this.getOrderList(_this.data.dataType);
          });
        }
      }
    });
  },

  /**
   * 发起付款
   */
  payOrder: function (e) {
    let _this = this;
    let order_id = e.currentTarget.dataset.id;

    // 显示loading
    wx.showLoading({
      title: '正在发起支付',
    });
    wx.requestPayment({
      timeStamp: Date.now(),
      nonceStr: "",
      package: "",
      signType: 'MD5',
      paySign: "",
      success: function (res) {
        // 跳转到已付款订单
        wx.navigateTo({
          url: '../order/detail?order_id=' + order_id
        });
      },
      fail: function () {
        wx.hideLoading({
          success: (res) => {
            App.showError('微信支付接口调用失败');
          },
        })
      },
    });
  },

  /**
   * 跳转详情页
   */
  detail: function (e) {
    let order_id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../goods/index?good_id=' + order_id
    });
  },

  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  }
});